package com.saturday.common.support;

import com.saturday.common.exception.UserContextLoseException;
import com.saturday.common.model.UserContext;
import com.saturday.common.util.SpringUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;

public class UserContextHolder {

    private static final ThreadLocal<String> userContextThreadLocalCache = new ThreadLocal<>();

    public static String getSessionId() {
        return userContextThreadLocalCache.get();
    }

    public static void setSessionId(String sessionId) {
        userContextThreadLocalCache.set(sessionId);
    }

    /**
     * 获取不到用户信息时将会抛出{@link UserContextLoseException}
     *
     * @return
     */
    public static UserContext get() {
        return getUserContext();
    }

    public static void clear() {
        userContextThreadLocalCache.remove();
    }

    private static UserContext getUserContext() {
        String sessionId = userContextThreadLocalCache.get();
        if (StringUtils.isEmpty(sessionId)) {
            throw UserContextLoseException.createException("无法获取当前用户信息");
        }
        ISessionCloudApi sessionCloudApi = SpringUtil.getBean(ISessionCloudApi.class);
        if (null == sessionCloudApi) {
            System.out.println("未发现用户信息获取的实现类, 需要引入saturday-auth-support包或者自行实现com.saturday.common.support.ISessionCloudApi");
        }
        return sessionCloudApi.getUserContextBySessionId(sessionId);
    }

    public static boolean isEmpty() {
        return StringUtils.isBlank(userContextThreadLocalCache.get());
    }
}
